/**
 * Ingenius-Group S.A.S
 *
 * Project: SAU
 * File: ListBox.java
 * Date: 14/03/2011
 */

package com.ingenius.sau.client.view.widgets;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;

/**
 * Class <strong>ListBox</strong>
 * 
 * @author Jesus David
 * @version 0.1
 */
public class ListBox extends SimpleComboBox<String> {

	private Map<String, String> map;

	public ListBox() {
		map = new HashMap<String, String>();
		setTriggerAction(TriggerAction.ALL);
	}

	@Override
	public void add(String value) {
		add(value, value);
	}

	public void add(String key, String value) {
		map.put(key, value);
		refresh();
	}

	@Override
	public void remove(String key) {
		String value = map.get(key);
		if (value != null) {
			map.remove(key);
			super.remove(value);
		}
	}

	@Override
	public void add(List<String> values) {
		for (String value : values) {
			add(value);
		}
	}

	@Override
	public void clear() {
		map.clear();
		super.clear();
		super.removeAll();
	}

	private void refresh() {
		super.removeAll();
		SortedSet<String> values = new TreeSet<String>(map.values());
		for (String value : values) {
			super.add(value);
		}
	}

	@Override
	public String getSimpleValue() {
		String result = "";
		String value = super.getSimpleValue();

		if (map.containsValue(value)) {
			for (String key : map.keySet()) {
				if (map.get(key).equals(value)) {
					result = key;
					break;
				}
			}
		}
		return result;
	}

	@Override
	public void setSimpleValue(String key) {
		String value = map.get(key);
		if (value != null && !value.isEmpty()) {
			super.setSimpleValue(value.toString());
		} else {
			super.setSimpleValue("---");
		}
	}

}
